<script setup lang="ts" name="Login">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, OfficeBuilding } from '@element-plus/icons-vue'
import { login, register } from '@/request/auth-api'
import { useAuthStore } from '@/store/modules/auth'

const router = useRouter()
const authStore = useAuthStore()

// 控制登录/注册切换
const activeTab = ref('login')

// 加载状态
const loading = ref(false)

// 表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 登录表单数据
const loginForm = reactive({
  login_name: '',
  password: ''
})

// 注册表单数据
const registerForm = reactive({
  login_name: '',
  full_name: '',
  password: '',
  confirm_password: '',
  department: ''
})

// 登录表单校验规则
const loginRules = {
  login_name: [
    { required: true, message: '请输入登录名', trigger: 'blur' },
    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于 6 个字符', trigger: 'blur' }
  ]
}

// 注册表单校验规则
const registerRules = {
  login_name: [
    { required: true, message: '请输入登录名', trigger: 'blur' },
    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
  ],
  full_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于 6 个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  department: [
    { required: true, message: '请输入部门', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async (e?: Event) => {
  // 确保防止任何可能导致页面刷新的行为
  if (e) e.preventDefault()
  
  if (!loginFormRef.value) return
  
  try {
    // 表单验证
    const valid = await loginFormRef.value.validate().catch(() => false)
    if (!valid) {
      console.log('表单验证失败')
      return
    }
    
    loading.value = true
    
    try {
      // 兼容修改后的登录API，同时传入username和login_name
      const res = await login({
        username: loginForm.login_name,  // 用username参数
        login_name: loginForm.login_name, // 也保留login_name参数
        password: loginForm.password
      })
      
      // 如果请求成功且返回了数据
      if (res.code === 0 && res.data) {
        // 保存token和用户信息
        authStore.setToken(res.data.access_token)
        authStore.setUserInfo(res.data.user)
        
        // 获取用户菜单权限
        try {
          await authStore.getMenuPermissions()
        } catch (err) {
          console.error('获取菜单权限失败:', err)
          ElMessage.warning('获取菜单权限失败，部分功能可能不可用')
        }
        
        ElMessage.success('登录成功')
        router.push('/dashboard')
      } else {
        // 登录失败显示错误信息
        ElMessage.error(res.errorMsg || '登录失败，请检查用户名和密码')
      }
    } catch (error: any) {
      // 处理API请求错误
      console.error('登录请求错误:', error)
      
      // 添加更详细的错误日志，帮助调试
      if (error.response) {
        console.log('响应状态码:', error.response.status)
        console.log('响应数据:', error.response.data)
      }
      
      // 优先使用后端返回的错误消息
      let errorMessage = '登录失败，请检查用户名和密码'
      
      if (error.response?.data?.errorMsg) {
        // 使用后端返回的错误消息
        errorMessage = error.response.data.errorMsg
      } else if (error.message) {
        // 使用axios拦截器中设置的错误消息
        errorMessage = error.message
      }
      
      // 显示错误消息，并增加持续时间
      ElMessage({
        message: errorMessage,
        type: 'error',
        duration: 5000,
        showClose: true
      })
    }
  } catch (error: any) {
    // 捕获所有其他错误
    console.error('登录过程发生错误:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
  
  // 返回false确保不会触发表单默认提交
  return false
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const res = await register({
          login_name: registerForm.login_name,
          full_name: registerForm.full_name,
          password: registerForm.password,
          confirm_password: registerForm.confirm_password,
          department: registerForm.department
        })
        
        if (res.code === 0) {
          ElMessage.success('注册成功，请登录')
          // 清空注册表单
          registerFormRef.value.resetFields()
          // 切换到登录页，并填入用户名
          activeTab.value = 'login'
          loginForm.login_name = registerForm.login_name
          loginForm.password = ''
        } else {
          ElMessage.error(res.errorMsg || '注册失败')
        }
      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error('注册失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>便利系统</h2>
        <p>用户登录/注册</p>
      </div>
      
      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 登录表单 -->
        <el-tab-pane label="登录" name="login">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-position="top"
            @submit.native.prevent="handleLogin"
          >
            <el-form-item label="登录名" prop="login_name">
              <el-input 
                v-model="loginForm.login_name"
                placeholder="请输入登录名"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                :loading="loading" 
                @click.stop.prevent="handleLogin"
                class="submit-btn"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 注册表单 -->
        <el-tab-pane label="注册" name="register">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            label-position="top"
          >
            <el-form-item label="登录名" prop="login_name">
              <el-input 
                v-model="registerForm.login_name"
                placeholder="请输入登录名"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="姓名" prop="full_name">
              <el-input 
                v-model="registerForm.full_name"
                placeholder="请输入姓名"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirm_password">
              <el-input 
                v-model="registerForm.confirm_password"
                type="password"
                placeholder="请确认密码"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="部门" prop="department">
              <el-input 
                v-model="registerForm.department"
                placeholder="请输入部门"
              >
                <template #prefix>
                  <el-icon><OfficeBuilding /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                :loading="loading" 
                @click="handleRegister"
                class="submit-btn"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 20px;
  
  h2 {
    font-size: 24px;
    color: #303133;
    margin-bottom: 10px;
  }
  
  p {
    font-size: 14px;
    color: #909399;
  }
}

.login-tabs {
  margin-top: 20px;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
}
</style>
